<template>
  <div class="shortMessage" v-loading="fullscreenLoading">
    <div class="part" v-loading="statsLoading">
      <div class="message">
        <p class="message-item">已发送短信（条）</p>
        <p class="message-desc">{{ stats.sendAll || 0 }}</p>
      </div>
      <div class="message">
        <p class="message-item">发送成功短信（条）</p>
        <p class="message-desc">{{ stats.successData || 0 }}</p>
      </div>
      <div class="message">
        <p class="message-item">发送失败短信（条）</p>
        <p class="message-desc">{{ stats.fail || 0 }}</p>
      </div>
      <div class="message">
        <p class="message-item">短信余量（条）</p>
        <p class="message-desc">{{ stats.balance || 0 }}</p>
      </div>
      <div class="operate">
        <el-button size="small" type="primary" @click="openRechargeDialog">短信充值</el-button>
      </div>
    </div>
    <div class="part">
      <el-form ref="form"
               :inline="true"
               class="search-form"
               :model="form">
        <el-form-item label="代理商" v-if="gradeOrigin === 3">
          <el-select v-model="form.sign" size="small" style="width: 175px">
            <el-option v-for="item in agentList"
                       :key="item.sign"
                       :label="item.company"
                       :value="item.sign"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="form.phone" size="small" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select size="small" v-model="form.state">
            <el-option label="全部" :value="3"></el-option>
            <el-option label="成功" :value="1"></el-option>
            <el-option label="失败" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发送时间">
          <el-date-picker
              v-model="date"
              size="small"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item style="margin-right: 0">
          <el-button size="small" type="primary" @click="search(1)">查询</el-button>
          <el-button size="small" @click="reset">显示全部</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="tableData" v-loading="loading">
      <el-table-column label="ID" prop="id" width="80px"/>
      <el-table-column label="手机号码" prop="phone" width="120px"/>
      <el-table-column label="内容" prop="content"/>
      <el-table-column label="发送时间" prop="create_time" width="200px"/>
      <el-table-column label="状态" prop="status" width="80px">
        <template slot-scope="prop">发送{{ prop.row.state === 1 ? '成功' : '失败' }}</template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
          background
          layout="total, prev, pager, next, jumper"
          :page-size.sync="form.size"
          :current-page.sync="form.page"
          :total="total"
          :hide-on-single-page="true"
          @current-change="search"
      />
    </div>
    <recharge-dialog ref="recharge" :agents="agentList" @success="search"/>
  </div>
</template>

<script>
import {pageSize} from "@/constant";
import rechargeDialog from './parts/recharge'
import {mapGetters} from "vuex";
import dayjs from "dayjs";
import './index.less'

export default {
  name: "index",
  data() {
    return {
      date: [
        dayjs().subtract(1, 'months').format('YYYY-MM-DD'),
        dayjs().format('YYYY-MM-DD')
      ],
      form: {
        size: pageSize,
        time_begin: '',
        time_end: '',
        phone: '',
        sign: '',
        state: 3
      },
      stats: {},
      tableData: [],
      total: 0,
      fullscreenLoading: false,
      statsLoading: false,
      loading: false,
      agentList: []
    }
  },
  computed: {
    ...mapGetters([
      'gradeOrigin'
    ])
  },
  watch: {
    'form.sign'() {
      this.getStats()
    },
    'form.size'() {
      this.search(1)
    },
    date: {
      immediate: true,
      deep: true,
      handler(date) {
        const [time_begin = '', time_end = ''] = date
        this.form.time_begin = time_begin
        this.form.time_end = time_end
      }
    }
  },
  async mounted() {
    let sign = ''
    // 系统管理员
    if (this.gradeOrigin === 3) {
      this.fullscreenLoading = true
      const agentList = await this.getAgents()
      this.fullscreenLoading = false
      if (agentList.length > 0) {
        sign = agentList[0].sign
      }
    } else {
      sign = 0
    }
    this.form.sign = sign
    this.search(1)
  },
  methods: {
    async getAgents() {
      let agentList = []
      await this.$axios.get('/api/v1/agents', {}).then(res => {
        let {total = 0, data = []} = res
        this.total = total
        agentList = data
      })
      this.agentList = agentList
      return agentList
    },
    reset() {
      this.form.sign = ''
      this.form.phone = ''
      this.form.time_begin = ''
      this.form.time_end = ''
      this.date = []
      this.form.state = 3
      this.search(1)
    },
    async search(page = 1) {
      this.loading = true
      let tableData = [],
          total = 0
      await this.$axios.get('/api/v1/sms/records', {
        params: {
          ...this.form,
          page
        },
        abort: true
      }).then(res => {
        total = res.total
        tableData = res.data || []
      })
      this.loading = false
      this.tableData = tableData
      this.total = total
    },
    async getStats() {
      const {sign} = this.form
      let stats = {}
      this.statsLoading = true
      await this.$axios.get('/api/v1/sms/statistic', {
        params: {
          sign: sign
        },
        abort: true
      }).then(res => {
        stats = res
      })
      this.statsLoading = false
      this.stats = stats
    },
    openRechargeDialog() {

      this.$refs.recharge.open(this.form.sign)
    }
  },
  components: {
    rechargeDialog
  }
}
</script>

<style lang="less">
.shortMessage {


  .message {
    padding: 0 20px;
    flex-grow: 1;
    flex-shrink: 1;
    max-width: 180px;
    text-align: center;

    &-item {
      color: #666;
      font-size: 12px;
    }

    &-desc {
      color: #222;
      font-size: 16px;
      margin-top: 8px;
      text-align: center;
    }

    & + .message {
      border-left: 1px solid #e2e2e2;
    }
  }

  .operate {
    flex-grow: 1;
    flex-shrink: 0;
    margin-left: 40px;
  }


}
</style>